﻿using Application.Abstractions.Authentication;
using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Todos;
using Domain.Users;
using Microsoft.EntityFrameworkCore;
using SharedKernel;

namespace Application.Todos.Create;

internal sealed class CreateTodoCommandHandler(
    IApplicationDbContext context,
    IDateTimeProvider dateTimeProvider,
    ICurrentUser currentUser)
    : ICommandHandler<CreateTodoCommand, Guid>
{
    public async ValueTask<Result<Guid>> Handle(CreateTodoCommand command, CancellationToken cancellationToken)
    {
        if (currentUser.UserId != command.UserId)
        {
            return Result.Failure<Guid>(UserErrors.Unauthorized());
        }

        User? user = await context.Users.AsNoTracking()
            .SingleOrDefaultAsync(u => u.Id == command.UserId, cancellationToken);

        if (user is null)
        {
            return Result.Failure<Guid>(UserErrors.NotFound(command.UserId));
        }

        // 创建新的待办事项 - 事件会在构造函数中自动触发
        var todoItem = new TodoItem(
            user.Id,
            command.Description,
            command.Priority,
            command.DueDate,
            command.Labels,
            dateTimeProvider);

        context.TodoItems.Add(todoItem);

        await context.SaveChangesAsync(cancellationToken);

        return todoItem.Id;
    }
}
